<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>访问统计可视化</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .header {
            background: #fff;
            border-bottom: 1px solid #e0e0e0;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
            color: #333;
        }
        
        .current-info {
            font-size: 16px;
            color: #666;
        }
        
        .tabs {
            display: flex;
            background: #fafafa;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .tab {
            flex: 1;
            padding: 16px;
            text-align: center;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            color: #666;
            transition: all 0.2s;
            border-bottom: 2px solid transparent;
        }
        
        .tab:hover {
            background: #f0f0f0;
        }
        
        .tab.active {
            color: #333;
            background: white;
            border-bottom-color: #333;
        }
        
        .content {
            padding: 30px;
        }
        
        .stats-summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: #fafafa;
            border: 1px solid #e0e0e0;
            padding: 20px;
            border-radius: 6px;
            text-align: center;
        }
        
        .stat-label {
            font-size: 13px;
            color: #999;
            margin-bottom: 8px;
        }
        
        .stat-value {
            font-size: 32px;
            font-weight: 600;
            color: #333;
        }
        
        .chart-container {
            height: 400px;
            margin-top: 20px;
        }
        
        .loading, .error, .empty {
            text-align: center;
            padding: 60px;
            color: #999;
            font-size: 16px;
        }
        
        .error {
            color: #f56c6c;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 访问统计可视化</h1>
            <div class="current-info" id="currentInfo">加载中...</div>
        </div>
        
        <div class="tabs">
            <div class="tab active" data-level="minute" onclick="switchTab('minute')">分钟级别</div>
            <div class="tab" data-level="hour" onclick="switchTab('hour')">小时级别</div>
            <div class="tab" data-level="day" onclick="switchTab('day')">天级别</div>
        </div>
        
        <div class="content">
            <div class="stats-summary" id="statsSummary"></div>
            <div class="chart-container" id="chart"></div>
        </div>
    </div>

    <script>
        let currentLevel = 'minute';
        let statsData = null;
        let chart = null;

        async function fetchStats() {
            try {
                const response = await fetch('/stats');
                if (!response.ok) throw new Error('获取数据失败');
                statsData = await response.json();
                updateDisplay();
            } catch (error) {
                document.getElementById('chart').innerHTML = '<div class="error">加载失败: ' + error.message + '</div>';
            }
        }

        function switchTab(level) {
            currentLevel = level;
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.toggle('active', tab.dataset.level === level);
            });
            updateDisplay();
        }

        function aggregateData(history, level) {
            const aggregated = {};
            
            history.forEach(item => {
                let key;
                if (level === 'minute') {
                    key = item.time;
                } else if (level === 'hour') {
                    key = item.time.substring(0, 13);
                } else if (level === 'day') {
                    key = item.time.substring(0, 10);
                }
                
                if (!aggregated[key]) {
                    aggregated[key] = 0;
                }
                aggregated[key] += item.count;
            });
            
            return Object.entries(aggregated)
                .map(([time, count]) => ({ time, count }))
                .sort((a, b) => a.time.localeCompare(b.time));
        }

        function formatTime(time, level) {
            if (level === 'minute') {
                return time.substring(11);
            } else if (level === 'hour') {
                return time.substring(11) + ':00';
            } else {
                return time.substring(5);
            }
        }

        function updateDisplay() {
            if (!statsData) return;

            document.getElementById('currentInfo').textContent = 
                `当前时间: ${statsData.current_minute} | 当前访问: ${statsData.current_count}`;

            const aggregated = aggregateData(statsData.history, currentLevel);
            
            if (aggregated.length === 0) {
                document.getElementById('chart').innerHTML = '<div class="empty">暂无历史数据</div>';
                document.getElementById('statsSummary').innerHTML = '';
                return;
            }

            const totalCount = aggregated.reduce((sum, item) => sum + item.count, 0);
            const maxCount = Math.max(...aggregated.map(item => item.count));
            const avgCount = (totalCount / aggregated.length).toFixed(1);

            document.getElementById('statsSummary').innerHTML = `
                <div class="stat-card">
                    <div class="stat-label">总访问量</div>
                    <div class="stat-value">${totalCount}</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">峰值访问</div>
                    <div class="stat-value">${maxCount}</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">平均访问</div>
                    <div class="stat-value">${avgCount}</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">数据点数</div>
                    <div class="stat-value">${aggregated.length}</div>
                </div>
            `;

            if (!chart) {
                chart = echarts.init(document.getElementById('chart'));
            }

            const option = {
                backgroundColor: '#fff',
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '10%',
                    top: '10%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: aggregated.map(item => formatTime(item.time, currentLevel)),
                    axisLine: { lineStyle: { color: '#ddd' } },
                    axisLabel: { color: '#666', fontSize: 12 },
                    axisTick: { show: false }
                },
                yAxis: {
                    type: 'value',
                    axisLine: { show: false },
                    axisLabel: { color: '#666', fontSize: 12 },
                    splitLine: { lineStyle: { color: '#f0f0f0' } }
                },
                series: [{
                    data: aggregated.map(item => item.count),
                    type: 'line',
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 6,
                    lineStyle: { color: '#666', width: 2 },
                    itemStyle: { color: '#666' },
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [
                                { offset: 0, color: 'rgba(102, 102, 102, 0.3)' },
                                { offset: 1, color: 'rgba(102, 102, 102, 0.05)' }
                            ]
                        }
                    }
                }],
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: 'rgba(50, 50, 50, 0.9)',
                    borderColor: '#333',
                    textStyle: { color: '#fff' }
                }
            };

            chart.setOption(option);
        }

        window.addEventListener('resize', () => {
            if (chart) chart.resize();
        });

        fetchStats();
        setInterval(fetchStats, 10000);
    </script>
</body>
</html>
